package com.nopay.cdxphone.ui.fragment;

import android.annotation.SuppressLint;
import android.view.View;
import android.view.animation.AlphaAnimation;

import androidx.annotation.ColorInt;
import androidx.annotation.ColorRes;
import androidx.core.content.ContextCompat;
import androidx.recyclerview.widget.GridLayoutManager;

import com.allenliu.versionchecklib.v2.AllenVersionChecker;
import com.azhon.basic.eventbus.MessageEvent;
import com.blankj.utilcode.util.SPUtils;
import com.blankj.utilcode.util.ToastUtils;
import com.bumptech.glide.Glide;
import com.nopay.cdxphone.Constants;
import com.nopay.cdxphone.R;
import com.nopay.cdxphone.base.BaseFragment;
import com.nopay.cdxphone.bean.CommonResponse;
import com.nopay.cdxphone.bean.SettingBean;
import com.nopay.cdxphone.bean.request.OpenMemberSuccessRequest;
import com.nopay.cdxphone.bean.response.LoginResponse;
import com.nopay.cdxphone.bean.response.OpenMemberSuccessResponse;
import com.nopay.cdxphone.databinding.FragmentPersonBinding;
import com.nopay.cdxphone.dialog.DialogContactCustomer;
import com.nopay.cdxphone.dialog.DialogMemberTrial;
import com.nopay.cdxphone.ui.adapter.SettingAdapter;
import com.nopay.cdxphone.ui.adapter.ViewBindingSampleAdapter;
import com.nopay.cdxphone.ui.ativity.MainActivity;
import com.nopay.cdxphone.utils.MemberManager;
import com.zhpan.bannerview.utils.BannerUtils;
import com.zhpan.indicator.enums.IndicatorSlideMode;

import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import okhttp3.RequestBody;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

/**
 * @ProjectName: guizhou_assets
 * @Package: dhc.guizhou.assets.view.main.fragment
 * @ClassName: HomeFragment
 * @Description: 我的
 * @Author: 安琪
 * @CreateDate: 2020-5-18 13:57
 * @UpdateUser: 更新者：
 * @UpdateDate: 2020-5-18 13:57
 * @UpdateRemark: 更新说明：
 * @Version: 1.0
 */
public class PersonFragment extends BaseFragment<FragmentPersonBinding> {

    @Override
    protected void loadData() {
        binding.rlRoot.setPadding(0, getStatusBarHeight(getActivity()), 0, 0);
        String userName = SPUtils.getInstance().getString(Constants.SP_USER_NAME, "用户名");
        String phone = SPUtils.getInstance().getString(Constants.SP_PHONE, "手机号");

        binding.tvTitle.setText(userName);
        binding.tvTel.setText(phone);

        setVIPStatus();
        setHeader();
        binding.rlTop.setOnClickListener(v -> ((MainActivity) getActivity()).gotoAcountInfo());

        binding.rv.setLayoutManager(new GridLayoutManager(getActivity(), 1));
        List<SettingBean> settingList = new ArrayList<>();
//        settingList.add(new SettingBean("开通会员", R.mipmap.icon_member));
        settingList.add(new SettingBean("防封设置", R.mipmap.icon_call_transfer_setting));
//        settingList.add(new SettingBean("防封使用说明", R.mipmap.icon_instructions));
        settingList.add(new SettingBean("邀请好友", R.mipmap.icon_invite_friends));
        settingList.add(new SettingBean("意见反馈", R.mipmap.icon_feedback));
        settingList.add(new SettingBean("联系客服", R.mipmap.icon_customer));
        settingList.add(new SettingBean("版本更新 ", ((MainActivity) getActivity()).getVersionName(), R.mipmap.icon_update));
        SettingAdapter adapter = new SettingAdapter(settingList);
        binding.rv.setAdapter(adapter);

        adapter.setOnItemChildClickListener((adapter1, view, position) -> {
            switch (position) {
//                case 0:
//                    ((MainActivity) getActivity()).gotoRecharge();
//                    break;

                case 0:
                    ((MainActivity) getActivity()).gotoCallSetting();
                    break;
//
//                case 1:
//                    ((MainActivity) getActivity()).gotoHelp();
//                    break;

                case 1:
                    ((MainActivity) getActivity()).gotoInvist();
                    break;

                case 2:
                    ((MainActivity) getActivity()).gotoFeedBack();
                    break;

                case 3:
                    api.doGetContactCustomer().enqueue(new Callback<CommonResponse>() {
                        @Override
                        public void onResponse(Call<CommonResponse> call, Response<CommonResponse> response) {
                            if (response.body() != null) {
                                if (Constants.RESULT_OK.equals(response.body().getCode())) {
                                    new DialogContactCustomer(getActivity()).show(response.body().getMsg());
                                } else {
                                    ToastUtils.showShort(response.body().getMsg());
                                }
                            }
                        }

                        @Override
                        public void onFailure(Call<CommonResponse> call, Throwable t) {
                            ToastUtils.showShort(getActivity().getResources().getString(R.string.call_api_error));
                        }
                    });
                    break;

                case 4:
                    // TODO 版本更新
                    ((MainActivity) getActivity()).checkVersion();
                    break;
            }
        });

        binding.tvMemberTrial.setOnClickListener(view -> {
            // TODO 试用会员
            setViewAnim(view);
            binding.tvMemberTrial.setEnabled(false);
            new DialogMemberTrial(getActivity()).setOnMemberTrialListener(confirm -> {
                // TODO 确定试用
                if(!confirm) {
                    binding.tvMemberTrial.setEnabled(true);
                    return;
                }

                OpenMemberSuccessRequest request = new OpenMemberSuccessRequest();
                request.setMemberId(1);
                request.setPhone(SPUtils.getInstance().getString(Constants.SP_PHONE));

                RequestBody body = getRequestBody(request);
                api.doMemberTrial(body).enqueue(new Callback<OpenMemberSuccessResponse>() {
                    @Override
                    public void onResponse(Call<OpenMemberSuccessResponse> call, Response<OpenMemberSuccessResponse> response) {
                        if (response.body() != null) {
                            if (Constants.RESULT_OK.equals(response.body().getCode())) {
                                doGetUserInfo();
                                return;
                            } else {
                                ToastUtils.showShort(response.body().getMsg());
                            }
                        } else {
                            ToastUtils.showShort("试用失败");
                        }
                        binding.tvMemberTrial.setEnabled(true);
                    }

                    @Override
                    public void onFailure(Call<OpenMemberSuccessResponse> call, Throwable t) {
                        binding.tvMemberTrial.setEnabled(true);
                        ToastUtils.showShort(getActivity().getResources().getString(R.string.call_api_error));
                    }
                });
            }).show();
        });

        binding.tvUserInfoSync.setOnClickListener(view -> {
            // TODO 刷新用户信息
            setViewAnim(view);
            doGetUserInfo();
        });

        binding.tvOpenVip.setOnClickListener(view -> {
            // TODO 开通会员
//            ((MainActivity) getActivity()).gotoRecharge();
            api.doGetContactCustomer().enqueue(new Callback<CommonResponse>() {
                @Override
                public void onResponse(Call<CommonResponse> call, Response<CommonResponse> response) {
                    if (response.body() != null) {
                        if (Constants.RESULT_OK.equals(response.body().getCode())) {
                            new DialogContactCustomer(getActivity()).show(response.body().getMsg());
                        } else {
                            ToastUtils.showShort(response.body().getMsg());
                        }
                    }
                }

                @Override
                public void onFailure(Call<CommonResponse> call, Throwable t) {
                    ToastUtils.showShort(getActivity().getResources().getString(R.string.call_api_error));
                }
            });

        });

        binding.bannerView
                .setIndicatorSlideMode(IndicatorSlideMode.SCALE)
                .setIndicatorSliderColor(getColor(R.color.red_normal_color), getColor(R.color.red_checked_color))
                .setIndicatorSliderRadius(getResources().getDimensionPixelOffset(R.dimen.dp_4), getResources().getDimensionPixelOffset(R.dimen.dp_5))
                .setLifecycleRegistry(getLifecycle())
                .setOnPageClickListener(this::pageClick)
                .setAdapter(new ViewBindingSampleAdapter(getResources().getDimensionPixelOffset(R.dimen.dp_8)))
                .setInterval(5000);

        mPictureList.add(R.mipmap.advertise2);

        binding.bannerView
                .setPageMargin(getResources().getDimensionPixelOffset(R.dimen.dp_15))
                .setRevealWidth(BannerUtils.dp2px(0))
                .setIndicatorSliderColor(getColor(R.color.red_normal_color), getColor(R.color.red_checked_color))
                .setOnPageClickListener((view, position) -> {
                    // TODO Banner点击事件

                })
                .setInterval(5000)
                .create(mPictureList);
        binding.bannerView.removeDefaultPageTransformer();
    }

    private void pageClick(View view, int position) {
        if (position != binding.bannerView.getCurrentItem()) {
            binding.bannerView.setCurrentItem(position, true);
        }
        ToastUtils.showShort("position:" + position);
    }

    protected ArrayList mPictureList = new ArrayList();

    protected ArrayList<Integer> getPicList(int count) {
        mPictureList.clear();
        for (int i = 0; i < count; i++) {
            int drawable = getResources().getIdentifier("advertise" + i, "mipmap", getContext().getPackageName());
            mPictureList.add(drawable);
        }
        return mPictureList;
    }

    @ColorInt
    protected int getColor(@ColorRes int colorRes) {
        return ContextCompat.getColor(getContext(), colorRes);
    }


    @Override
    public void onDestroyView() {
        super.onDestroyView();
        //合适的地方关闭
        AllenVersionChecker.getInstance().cancelAllMission();
    }

    private void setHeader(){
        String headUrl = SPUtils.getInstance().getString(Constants.SP_HEAD_URL, "");
        headUrl = headUrl.replace("127.0.0.1","43.249.192.38");
        Glide.with(getActivity()).load(headUrl).error(R.mipmap.icon_default_user)
                .placeholder(R.mipmap.icon_default_user).fallback(R.mipmap.icon_default_user).into(binding.rivHead);
    }

    private void setVIPStatus(){
//        binding.tvMemberLevel.setVisibility(SPUtils.getInstance().getInt(Constants.SP_VIP_STATUS, 0) == 1 ? View.VISIBLE : View.GONE);
//        binding.tvMemberExpire.setVisibility(SPUtils.getInstance().getInt(Constants.SP_VIP_STATUS, 0) == 1 ? View.VISIBLE : View.GONE);
//        binding.tvMemberLevel.setText(SPUtils.getInstance().getString(Constants.SP_VIP_LEVEL, ""));

//        binding.tvMemberTrial.setVisibility(MemberManager.hasMemberTrialPermission() ? View.VISIBLE : View.GONE);
        int vipStatus = SPUtils.getInstance().getInt(Constants.SP_VIP_STATUS, 0);
        boolean isVip = vipStatus == 1 || vipStatus == 2;
        binding.tvMember.setVisibility(isVip ? View.VISIBLE : View.GONE);
        binding.tvMember.setText("会员到期：" + getDateByVIPInvalidTime());
    }

    @SuppressLint("SimpleDateFormat")
    private String getDateByVIPInvalidTime() {
        String invalidTime = SPUtils.getInstance().getString(Constants.SP_VIP_INVALID_TIME, "");
        if(!"".equals(invalidTime)) {
            try {
                Date date = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").parse(invalidTime);
                return new SimpleDateFormat("yyyy-MM-dd").format(date);
            } catch (ParseException e) {
                e.printStackTrace();
            }
        }
        return "";
    }

    @Override
    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onDataEvent(MessageEvent msg) {
        super.onDataEvent(msg);
        switch (msg.msgType) {
            case MessageEvent.TYPE_CHANGE_HEAD:
                setHeader();
                break;

            case MessageEvent.TYPE_CHANGE_VIP_STATUS:
                setVIPStatus();
                break;
        }
    }

    private void doGetUserInfo() {
        ToastUtils.showShort("用户信息同步中...");
        long userId = SPUtils.getInstance().getLong(Constants.SP_USER_ID, -1L);
        api.doGetUserInfo(userId).enqueue(new Callback<LoginResponse>() {
            @Override
            public void onResponse(Call<LoginResponse> call, Response<LoginResponse> response) {
                if (response.body() != null) {
                    if (Constants.RESULT_OK.equals(response.body().getCode())) {
                        long userId = response.body().getData().getId();
                        String userName = response.body().getData().getUserName();
                        String phone = response.body().getData().getPhone();
                        String headUrl = response.body().getData().getHeadUrl();
                        String companyName = response.body().getData().getCompanyName();
                        int status = response.body().getData().getStatus();
                        String memberLevel = response.body().getData().getMemberLevel();
                        String invalidTime = response.body().getData().getInvalidTime();
                        SPUtils.getInstance().put(Constants.SP_USER_ID, userId);
                        SPUtils.getInstance().put(Constants.SP_USER_NAME, userName);
                        SPUtils.getInstance().put(Constants.SP_PHONE, phone);
                        SPUtils.getInstance().put(Constants.SP_HEAD_URL, headUrl);
                        SPUtils.getInstance().put(Constants.SP_COMPANY_NAME, companyName);
                        SPUtils.getInstance().put(Constants.SP_VIP_STATUS, status);
                        SPUtils.getInstance().put(Constants.SP_VIP_LEVEL, memberLevel);
                        SPUtils.getInstance().put(Constants.SP_VIP_INVALID_TIME, invalidTime);

                        binding.tvTitle.setText(SPUtils.getInstance().getString(Constants.SP_USER_NAME, "用户名"));
                        binding.tvTel.setText(SPUtils.getInstance().getString(Constants.SP_PHONE, "手机号"));
                        setVIPStatus();
                        setHeader();
                        ToastUtils.showShort("用户信息同步完成");
                    } else {
                        ToastUtils.showShort(response.body().getMsg());
                    }
                } else {
                    ToastUtils.showShort("用户信息同步出错");
                }
            }

            @Override
            public void onFailure(Call<LoginResponse> call, Throwable t) {
                ToastUtils.showShort(getActivity().getResources().getString(R.string.call_api_error));
            }
        });
    }

    /**
     * 设置View点击效果
     * @param view
     */
    public void setViewAnim(View view) {
        AlphaAnimation alphaAnimation = new AlphaAnimation(0.5f, 1.0f);
        alphaAnimation.setDuration(200);
        view.startAnimation(alphaAnimation);
    }
}
